import {Message} from 'element-ui'

var ws;
var tt;
var lockReconnect = false;//避免重复连接
var clientId = localStorage.getItem("clientId")//缓存中取出客户端id
var timeout = 1000 * 60 * 3;
var timeoutObj = null;
var serverTimeoutObj = null;
var websocket = {
    Init: function (url) {
        if ("WebSocket" in window) {
            ws = new WebSocket(url);
        } else {
            console.log("您的浏览器不支持 WebSocket!");
            return;
        }

        ws.onmessage = function (e) {
            console.log("接收消息:" + e.data)
            var data = JSON.parse(e.data)
            if (data.type === '1000') {
                console.log('心跳检测')
            }
            heartCheck.start();
        }

        ws.onclose = function () {
            console.log("连接已关闭")
            Message({
                message: '连接已关闭',
                type: 'error',
            });
            reconnect(clientId);
        }

        ws.onopen = function () {
            console.log("连接成功")
            Message({
                message: '连接成功',
                type: 'success',
            });
            heartCheck.start();
        }

        ws.onerror = function () {
            console.log("数据传输发生错误");
            Message({
                message: '数据传输发生错误',
                type: 'error',
            });
            reconnect(clientId)
        }
    },
    Send: function (type, datas) {
        let data = {
            type: type,
            data: datas,
        }
        let msg = JSON.stringify(data)
        console.log("发送消息：" + msg)
        ws.send(msg)
    },
    start() {
        console.log('开始心跳检测');
        timeoutObj && clearTimeout(this.timeoutObj);
        serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        timeoutObj = setTimeout(function () {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
            console.log('心跳检测...');
            ws.send("{type:'1000'}");
            serverTimeoutObj = setTimeout(function () {
                if (ws.readyState != 1) {
                    ws.close();
                }
            }, timeout);

        }, timeout)
    },
    getWebSocket() {
        return ws;
    },
    getStatus() {
        if (ws.readyState == 0) {
            return "未连接";
        } else if (ws.readyState == 1) {
            return "已连接";
        } else if (ws.readyState == 2) {
            return "连接正在关闭";
        } else if (ws.readyState == 3) {
            return "连接已关闭";
        }
    }
}

export default websocket;


function reconnect(sname) {
    if (lockReconnect) {
        return;
    }
    lockReconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    tt && clearTimeout(tt);
    tt = setTimeout(function () {
        console.log("执行断线重连...")
        websocket.Init(sname);
        lockReconnect = false;
    }, 4000);
}

//心跳检测
export var heartCheck = {
    timeout: 1000 * 60 * 3,
    timeoutObj: null,
    serverTimeoutObj: null,
    start: function () {
        console.log('开始心跳检测');
        var self = this;
        this.timeoutObj && clearTimeout(this.timeoutObj);
        this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        this.timeoutObj = setTimeout(function () {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
            console.log('心跳检测...');
            ws.send("{type:'1000'}");
            self.serverTimeoutObj = setTimeout(function () {
                if (ws.readyState != 1) {
                    ws.close();
                }
            }, self.timeout);

        }, this.timeout)
    }
}

